package com.think.common.utils;

import com.think.common.model.CustomUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;


public class Common {

	public static final Integer USER_PHONE_LOGIN = 1;
	public static final Integer USER_WX_LOGIN = 2;
	public static final Integer USER_USERNAME_LOGIN = 3;
	public static final Integer USER_ILAB_LOGIN = 4;
	public static final Integer USER_EMAIL_LOGIN = 5;
	public static final Integer USER_QH_CAS_LOGIN = 6;

	public static CustomUser GetCurrentAuthor() {
		try {
			OAuth2Authentication authentication = (OAuth2Authentication)SecurityContextHolder.getContext().getAuthentication();
			Object user = authentication.getPrincipal();
			return (CustomUser)user;
		} catch (Exception e) {
			return new CustomUser("anymous", "", null, USER_USERNAME_LOGIN, -1);
		}
		
	}
	
	public static String GetClient() {
		try {
			OAuth2Authentication authentication = (OAuth2Authentication)SecurityContextHolder.getContext().getAuthentication();
			return authentication.getOAuth2Request().getClientId();
		} catch (Exception e) {
			HttpServletRequest request =((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			return request.getParameter("client_id");
		}
	}

	public static boolean IsRootAdmin(){
		for (GrantedAuthority grantedAuthority:GetCurrentAuthor().getAuthorities()){
			if(grantedAuthority.getAuthority().equals("ROLE_ADMIN"))
				return true;
		}
		return false;
	}
	
	public static boolean HasRole(String role){
		for (GrantedAuthority grantedAuthority:GetCurrentAuthor().getAuthorities()){
			if(grantedAuthority.getAuthority().equals(role))
				return true;
		}
		return false;
	}

	public static boolean IsEmailAddress(String address) {
		String mailRegex,mailName,mailDomain;
        mailName="^[0-9a-z]+\\w*";       //^表明一行以什么开头；^[0-9a-z]表明要以数字或小写字母开头；\\w*表明匹配任意个大写小写字母或数字或下划线
        mailDomain="([0-9a-z]+\\.)+[0-9a-z]+$";       //***.***.***格式的域名，其中*为小写字母或数字;第一个括号代表有至少一个***.匹配单元，而[0-9a-z]$表明以小写字母或数字结尾
        mailRegex=mailName+"@"+mailDomain;          //邮箱正则表达式      ^[0-9a-z]+\w*@([0-9a-z]+\.)+[0-9a-z]+$
        Pattern pattern=Pattern.compile(mailRegex);
        return pattern.matcher(address).matches();
	} 
}
